<?php 
namespace app\publictool\controller;
 
 use Qiniu\Auth;
 use Qiniu\Storage\UploadManager;
 use think\exception\HttpException; //http 错误警告
class Qiniu{
  protected $auth; //上传认证
  protected $accessKey=''; //用户名
  protected $secretKey=''; //密码
  protected $filePath = ''; //图片地址
  protected $bucke=''; //空间
  protected $uploadToken = ''; //上传token
  protected $fileName = ''; //文件名称
  protected $uploadMg = '';
  protected $autoCreateFileName=true; //自动创建文件名
   /**
    * @param void
    * @return void
    * 七牛上传构造函数（初始化）
    * [__construct description]
    */
  public function __construct(){
  	 $this->accessKey = config('qiniu.accessKey');
  	 $this->secretKey = config('qiniu.secretKey');
  	 $this->bucket = config('qiniu.bucket');
  	 $this->filePath = config('qiniu.file_path');
  	 $this->auth = new Auth($this->accessKey,$this->secretKey);
  	 $this->createUploadToken();
  	 $this->uploadMg = new UploadManager();
  }


  public  function upload($fileInfo=null){
  		 $result = ''; //成功后的返回值
  		 $error = ''; //失败后的返回值
    	 if(is_null($fileInfo)){
    	 	throw new HttpException(-0001,'没有上传文件！');
    	 }

    	 if(empty($fileInfo)){
    	 	throw new HttpException(-0003,'没有上传文件！');
    	 }

    	 if($this->autoCreateFileName){
    	 	//如果为空默认生成哈希值为名称以时间戳为准
    	 	$this->autoCreateFileName();
    	 }

    	 $this->getFilePath($fileInfo); //获取上传的文件临时路径
    	 //上传赋值
    	 list($result,$error) = $this->uploadMg->putFile($this->uploadToken,$this->fileName,$this->filePath);
    	 if($error  !==  null){
    	 	throw new HttpException(-0002,'上传失败！');
    	 }
	 	return $result;
  }

  //生成上传的token
  private function createUploadToken(){
  	 $this->uploadToken = $this->auth->uploadToken($this->bucket);
  }

 //自动创建文件名称
 private  function autoCreateFileName($name=null){
 	$time = time();
 	$microtime = microtime();
 	$this->fileName=sha1(($time.$microtime));
 }

  //获取文件的路径
  private function getFilePath($fileInfo){
  	 $this->fileName = array_column($fileInfo,'name')[0];
  	 $this->filePath = array_column($fileInfo,'tmp_name')[0];
  	 return;
  }
} 